﻿using Android.App;
using Android.Content;
using Android.Locations;
using Android.OS;
using Android.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Teriri.File.Client.Maui
{
    /// <summary>
    /// 自定义卫星信息回调
    /// </summary>
    public class SatelliteCallback : GnssStatus.Callback
    {
        private static SatelliteInfo Satellite;

        private static bool IsFirst = true;

        /// <summary>
        /// 注册函数
        /// </summary>
        public static void RegisterGnssStatusCallback()
        {
            if (IsFirst == false)
                return;

#if ANDROID
            // 注册回调函数，如果有定位请求，就会变化
            var locationManager = (LocationManager)Android.App.Application.Context.GetSystemService(Context.LocationService);
            locationManager.RegisterGnssStatusCallback(new SatelliteCallback());
#endif

            IsFirst = false;
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        public static SatelliteInfo GetSatelliteInfo()
        {
            return Satellite;
        }

        /// <summary>
        /// 私有构造函数
        /// </summary>
        private SatelliteCallback()
        {
        }

        /// <summary>
        /// 重写卫星信息变化事件
        /// </summary>
        public override void OnSatelliteStatusChanged(GnssStatus status)
        {
            var info = new SatelliteInfo();

            info .TotalCount = status.SatelliteCount;

            for (int i = 0; i < info.TotalCount; i++)
            {
                var type =  status.GetConstellationType(i);

                if (info.GnssConstellationStatistics.ContainsKey(type))
                    info.GnssConstellationStatistics[type]++;
                else
                    info.GnssConstellationStatistics[type] = 1;
            }

            Satellite = info;
        }
    }

    /// <summary>
    /// 卫星信息
    /// </summary>
    public class SatelliteInfo
    {
        /// <summary>
        /// 分类统计
        /// </summary>
        public Dictionary<GnssConstellationType, int> GnssConstellationStatistics { get; set; } = new();

        /// <summary>
        /// 全部卫星数量
        /// </summary>
        public int TotalCount { get; set; } = 0;

        /// <summary>
        /// 数据时间
        /// </summary>
        public DateTime Time = DateTime.Now;
    }
}
